#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QString ac,int r,QSqlDatabase* db,QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setCentralWidget(ui->stackedWidget);

    m_account = ac;
    m_role = r;
    m_db = *db;

    iniUI();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::iniUI()
{

    ui->tvBook->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tvUser->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tvOrder->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tvUserOrder->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);




    //初始化数据表
    m_bookModel = new QSqlTableModel(this);
    m_userModel = new QSqlTableModel(this);
    m_orderModel = new QSqlTableModel(this);

    m_bookModel->setTable("tb_book");
    m_userModel->setTable("tb_user");
    m_orderModel->setTable("tb_order");

    m_bookModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    m_userModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    m_orderModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    m_bookModel->select();
    m_userModel->select();
    m_orderModel->select();

    m_bookModel->setHeaderData(0,Qt::Horizontal,"编号",Qt::DisplayRole);
    m_bookModel->setHeaderData(1,Qt::Horizontal,"类型",Qt::DisplayRole);
    m_bookModel->setHeaderData(2,Qt::Horizontal,"名称",Qt::DisplayRole);
    m_bookModel->setHeaderData(3,Qt::Horizontal,"数量",Qt::DisplayRole);
    m_bookModel->setHeaderData(4,Qt::Horizontal,"价格",Qt::DisplayRole);

    m_userModel->setHeaderData(0,Qt::Horizontal,"编号",Qt::DisplayRole);
    m_userModel->setHeaderData(1,Qt::Horizontal,"账号",Qt::DisplayRole);
    m_userModel->setHeaderData(2,Qt::Horizontal,"密码",Qt::DisplayRole);
    m_userModel->setHeaderData(3,Qt::Horizontal,"名称",Qt::DisplayRole);

    m_orderModel->setHeaderData(0,Qt::Horizontal,"编号",Qt::DisplayRole);
    m_orderModel->setHeaderData(1,Qt::Horizontal,"状态",Qt::DisplayRole);
    m_orderModel->setHeaderData(2,Qt::Horizontal,"用户",Qt::DisplayRole);
    m_orderModel->setHeaderData(3,Qt::Horizontal,"购物",Qt::DisplayRole);
    m_orderModel->setHeaderData(4,Qt::Horizontal,"支付状态",Qt::DisplayRole);
    m_orderModel->setHeaderData(5,Qt::Horizontal,"时间",Qt::DisplayRole);


    ui->tvOrder->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tvUserOrder->setEditTriggers(QAbstractItemView::NoEditTriggers);


    ui->tvBook->setModel(m_bookModel);
    ui->tvUser->setModel(m_userModel);
    ui->tvOrder->setModel(m_orderModel);

    ui->stackedWidget->setCurrentWidget(ui->pagBook);

    for(int i = 0;i < m_bookModel->rowCount(); ++i){
        QString tempStr = m_bookModel->data(m_bookModel->index(i,1)).toString();
        if(!m_bookTypeList.contains(tempStr)){
            m_bookTypeList.append(tempStr);
        }
    }
    ui->combBookType->addItems(m_bookTypeList);

    //根据登陆的用户类型进行不同的初始化
    if(m_role == 0){
        this->setWindowTitle("欢迎使用图书管理系统!@管理员"+m_account);
        ui->groupUserBuy->hide();
        ui->tBarUser->hide();

    }else{
        this->setWindowTitle("欢迎使用图书管理系统!@用户"+m_account);

        ui->groupAdminMange->hide();
        ui->tbarAdmin->hide();
        ui->tvBook->setEditTriggers(QAbstractItemView::NoEditTriggers);//设置书籍视图不可编辑
    }


}

QStringList MainWindow::analyShopBox(QString s)
{
    QStringList tempList;
    tempList = s.simplified().split("&");

    return tempList;
}


void MainWindow::on_actBookManage_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pagBook);
}


void MainWindow::on_actOrderManage_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pagOrder);
}


void MainWindow::on_actUserManage_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pagUser);
}


void MainWindow::on_btnAppendBook_clicked()
{
    m_bookModel->insertRow(m_bookModel->rowCount());
}


void MainWindow::on_btnDeleteBook_clicked()
{

    if(ui->tvBook->currentIndex().isValid() == true){
        m_bookModel->removeRow(ui->tvBook->currentIndex().row());
    }
}


void MainWindow::on_btnResetBook_clicked()
{
    m_bookModel->select();
}


void MainWindow::on_btnSubmitBook_clicked()
{
    if(m_bookModel->isDirty() == true){
        m_bookModel->submitAll();
        QMessageBox::information(0,"提示","数据提交成功!");

        m_bookTypeList.clear();
        ui->combBookType->clear();
        ui->combBookType->addItem("所有书籍");
        for(int i = 0;i < m_bookModel->rowCount(); ++i){
            QString tempStr = m_bookModel->data(m_bookModel->index(i,1)).toString();
            if(!m_bookTypeList.contains(tempStr)){
                m_bookTypeList.append(tempStr);
            }
        }
        ui->combBookType->addItems(m_bookTypeList);
    }
}


void MainWindow::on_btnAppendUser_clicked()
{
    m_userModel->insertRow(m_userModel->rowCount());
}


void MainWindow::on_btnDeleteUser_clicked()
{
    if(ui->tvUser->currentIndex().isValid() == true){
        m_userModel->removeRow(ui->tvUser->currentIndex().row());
    }
}


void MainWindow::on_btnResetUser_clicked()
{
    m_userModel->select();
}


void MainWindow::on_btnSubmitUser_clicked()
{
    if(m_userModel->isDirty() == true){
        m_userModel->submitAll();
        QMessageBox::information(0,"提示","数据提交成功!");
    }
}


void MainWindow::on_checkBox_stateChanged(int arg1)
{
    if(arg1 == 0){//如果未选中
        for(int i = 0;i < m_orderModel->rowCount(); ++i){
            ui->tvOrder->showRow(i);
        }

    }else{
        for(int i = 0; i < m_orderModel->rowCount(); ++i){
            if(m_orderModel->data(m_orderModel->index(i,1)).toInt() != 0){
                ui->tvOrder->hideRow(i);
            }
        }
    }
}


void MainWindow::on_tvOrder_doubleClicked(const QModelIndex &index)
{
    ui->btnIgnorePay->hide();
    ui->btnPay->hide();

    int row = index.row();

    ui->labOrderId->setText(m_orderModel->data(m_orderModel->index(row,0)).toString());//订单id

    QStringList shopBox = analyShopBox(m_orderModel->data(m_orderModel->index(row,3)).toString());
    QSqlQuery query;
    QString tempStr;
    QStringList tempList;
    double totalPrice = 0;
    for(int i = 0;i < shopBox.count(); ++i){
        tempList = shopBox.at(i).split("*");
        query.exec("select name,price from tb_book where id="+QString::asprintf("%d",tempList.at(0).toInt()));
        query.first();
        if(query.isValid()){
            tempStr += query.value("name").toString()+"X"+tempList.at(1)+" ";
            totalPrice += tempList.at(1).toInt()*query.value("price").toDouble();
        }

    }
    ui->labShopBox->setText(tempStr);//购物车


    if(m_orderModel->data(m_orderModel->index(row,1)).toInt() == 1){//审核状态
        ui->labAuditState->setText("已通过");
        ui->btnIgnore->setEnabled(false);
        ui->btnPass->setEnabled(false);
    }else{
        ui->labAuditState->setText("待审核");
        ui->btnIgnore->setEnabled(true);
        ui->btnPass->setEnabled(true);
    }

    ui->labTotalPrice->setText(QString::asprintf("%.2f",totalPrice));//总价
    if(m_orderModel->data(m_orderModel->index(row,4)).toInt() == 0){//支付状态
        ui->labPayState->setText("未支付");
    }else{
        ui->labPayState->setText("已支付");
    }


    query.exec("select name from tb_user where id="+QString::asprintf("%d",m_orderModel->data(m_orderModel->index(row,2)).toInt()));
    query.first();
    if(query.isValid()){
        ui->labUserName->setText(query.value("name").toString());//用户姓名
    }
    ui->labTime->setText(m_orderModel->data(m_orderModel->index(row,5)).toString());//生成时间


    ui->stackedWidget->setCurrentWidget(ui->pagOrderDetail);
}


void MainWindow::on_btnIgnore_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->pagOrder);
}


void MainWindow::on_btnPass_clicked()
{
    QSqlQuery query;
    if(query.exec("update tb_order set state=1 where id="+ui->labOrderId->text()+";") == false){
        QMessageBox::warning(0,"警告","订单修改失败.");
        return;
    }

    ui->stackedWidget->setCurrentWidget(ui->pagOrder);
}


void MainWindow::on_stackedWidget_currentChanged(int arg1)
{
    Q_UNUSED(arg1);
    if(ui->stackedWidget->currentWidget() == ui->pagOrder){
        m_orderModel->select();
    }
}


void MainWindow::on_combBookType_currentTextChanged(const QString &arg1)
{



    if(arg1 != "所有书籍"){//隐藏非指定行
        for(int i = 0;i < m_bookModel->rowCount(); ++i){//显示所有行
            ui->tvBook->setRowHidden(i,false);
        }

        for(int i = 0;i < m_bookModel->rowCount(); ++i){
            if(m_bookModel->data(m_bookModel->index(i,1)).toString() != arg1 || !m_bookModel->data(m_bookModel->index(i,2)).toString().contains(ui->editFInd->text())){
                ui->tvBook->setRowHidden(i,true);
            }
        }
    }else{
        for(int i = 0; i < m_bookModel->rowCount(); ++i){//隐藏所有行
            ui->tvBook->setRowHidden(i,true);
        }

        for(int i = 0; i < m_bookModel->rowCount(); ++i){
            if(m_bookModel->data(m_bookModel->index(i,2)).toString().contains(ui->editFInd->text())){
                ui->tvBook->setRowHidden(i,false);
            }
        }
    }
}


void MainWindow::on_btnFind_clicked()
{
    if(ui->editFInd->text().isEmpty() == true){
        for(int i = 0; i < m_bookModel->rowCount(); ++i){//显示所有行
            ui->tvBook->setRowHidden(i,false);
        }
        ui->combBookType->currentTextChanged(ui->combBookType->currentText());
        return;
    }

    for(int i = 0; i < m_bookModel->rowCount(); ++i){//隐藏所有行
        ui->tvBook->setRowHidden(i,true);
    }
    if(ui->combBookType->currentText() == "所有书籍"){
        ui->tvBook->clearSelection();
        for(int i = 0; i < m_bookModel->rowCount(); ++i){
            if(m_bookModel->data(m_bookModel->index(i,2)).toString().contains(ui->editFInd->text())){
                ui->tvBook->setRowHidden(i,false);
            }
        }
    }else{
        ui->tvBook->clearSelection();
        for(int i = 0; i < m_bookModel->rowCount(); ++i){
            if(m_bookModel->data(m_bookModel->index(i,2)).toString().contains(ui->editFInd->text()) && (m_bookModel->data(m_bookModel->index(i,1)).toString() ==  ui->combBookType->currentText())){
                ui->tvBook->setRowHidden(i,false);
            }
        }
    }


}


void MainWindow::on_btnAppendBox_clicked()
{
    if(!ui->tvBook->currentIndex().isValid()){//如果没选择书籍就不采取行动
        return;
    }

    int row = ui->tvBook->currentIndex().row();
    int maxCount = m_bookModel->data(m_bookModel->index(row,3)).toInt();
    QString bookName = m_bookModel->data(m_bookModel->index(row,2)).toString();
    if(ui->spinBuyCount->value() > maxCount){//如果购买数量超出库存
        QMessageBox::warning(0,"警告","库存不足,无法添加至购物车.");
        return;
    }

    for(int i = 0; i < ui->widgetBuy->count(); ++i){
        QString tempStr = ui->widgetBuy->item(i)->text();
        if(tempStr.contains(bookName)){
            QMessageBox::warning(0,"警告","无法添加同一书籍两次.");
            return;
        }
    }



    ui->widgetBuy->addItem(bookName+"*"+ui->spinBuyCount->text());
    ui->tvBook->clearSelection();

}


void MainWindow::on_actBuyBook_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->pagBook);
}


void MainWindow::on_btnClearBox_clicked()
{
    ui->widgetBuy->clear();
}


void MainWindow::on_btnOrder_clicked()
{
    if(ui->widgetBuy->count() == 0){
        return;
    }

    QString resultStr;
    QString tempStr;
    QString tempBook;
    QStringList tempStrList;
    QStringList queryList;

    int rowItem = ui->widgetBuy->count();
    int rowModel = m_bookModel->rowCount();
    for(int i = 0;i < rowItem; ++i){
        tempStr = ui->widgetBuy->item(i)->text();
        tempStrList = tempStr.split("*");
        tempBook = tempStrList.at(0);
        for(int i = 0;i < rowModel; ++i){
            if(m_bookModel->data(m_bookModel->index(i,2)).toString().contains(tempBook)){
                resultStr += m_bookModel->data(m_bookModel->index(i,0)).toString() +"*"+tempStrList.at(1)+"&";
                queryList.append("update tb_book set count="+QString::asprintf("%d",m_bookModel->data(m_bookModel->index(i,3)).toInt()-tempStrList.at(1).toInt())+" where id="+m_bookModel->data(m_bookModel->index(i,0)).toString()+";");
                break;
            }
        }
    }
    resultStr.remove(resultStr.count()-1,1);//移除多余的字符

    QSqlQuery query;
    QString userId;
    if(query.exec("select id from tb_user where account='"+m_account+"';") == false){
        QMessageBox::warning(0,"警告","数据库检索失败.");
    }
    query.first();
    if(query.isValid()){
        userId = query.value("id").toString();
    }else{
        QMessageBox::warning(0,"警告","数据检索出错!");
        return;
    }

    if(query.exec("insert into tb_order(userid,buy) values("+userId+",'"+resultStr+"');") == true){
        QMessageBox::information(0,"提示","下单成功!请及时缴费.");

        for(int i = 0;i < queryList.count(); ++i){
            query.exec(queryList.at(i));
        }

        m_bookModel->select();
        m_orderModel->select();
    }else{
        QMessageBox::warning(0,"","");
    }

}


void MainWindow::on_actMyorder_triggered()
{
    QString userId;
    QSqlQuery query;
    if(query.exec("select id from tb_user where account='"+m_account+"';") == false){
        QMessageBox::warning(0,"警告","数据库检索失败.");
        return;
    }
    query.first();
    if(query.isValid()){
        userId = query.value("id").toString();
    }else{
        QMessageBox::warning(0,"警告","数据检索出错!");
        return;
    }

    QStandardItemModel* theModel = new QStandardItemModel(this);
    theModel->setColumnCount(m_orderModel->columnCount());
    for(int i = 0;i < m_orderModel->columnCount(); ++i){
        theModel->setHeaderData(i,Qt::Horizontal,m_orderModel->headerData(i,Qt::Horizontal));
    }


    for(int i = 0;i < m_orderModel->rowCount(); ++i){
        if(m_orderModel->data(m_orderModel->index(i,2)).toInt() == userId.toInt()){
            QList<QStandardItem*> theList;
            for(int j = 0;j < m_orderModel->columnCount();++j){
                QStandardItem* aitem = new QStandardItem;
                aitem->setText(m_orderModel->data(m_orderModel->index(i,j)).toString());
                theList.append(aitem);
            }
            theModel->appendRow(theList);
        }
    }

    ui->tvUserOrder->setModel(theModel);
    ui->stackedWidget->setCurrentWidget(ui->pagUserOrder);
}


void MainWindow::on_tvUserOrder_doubleClicked(const QModelIndex &index)
{
    ui->btnPass->hide();
    ui->btnIgnore->hide();

    QStandardItemModel* theModel = (QStandardItemModel*)ui->tvUserOrder->model();
    int tempId = theModel->data(theModel->index(index.row(),0)).toInt();
    int row = -1;
    for(int i = 0;i < m_orderModel->rowCount(); ++i){
        if(m_orderModel->data(m_orderModel->index(i,0)).toInt() == tempId){
            row = i;
            break;
        }
    }

    if(row == -1){//如果程序逻辑出错
        return;
    }

    ui->labOrderId->setText(m_orderModel->data(m_orderModel->index(row,0)).toString());//订单id

    QStringList shopBox = analyShopBox(m_orderModel->data(m_orderModel->index(row,3)).toString());
    QSqlQuery query;
    QString tempStr;
    QStringList tempList;
    double totalPrice = 0;
    for(int i = 0;i < shopBox.count(); ++i){
        tempList = shopBox.at(i).split("*");
        query.exec("select name,price from tb_book where id="+QString::asprintf("%d",tempList.at(0).toInt()));
        query.first();
        if(query.isValid()){
            tempStr += query.value("name").toString()+"X"+tempList.at(1)+" ";
            totalPrice += tempList.at(1).toInt()*query.value("price").toDouble();
        }

    }
    ui->labShopBox->setText(tempStr);//购物车


    if(m_orderModel->data(m_orderModel->index(row,1)).toInt() == 1){//审核状态
        ui->labAuditState->setText("已通过");

    }else{
        ui->labAuditState->setText("待审核");

    }

    ui->labTotalPrice->setText(QString::asprintf("%.2f",totalPrice));//总价
    if(m_orderModel->data(m_orderModel->index(row,4)).toInt() == 0){//支付状态
        ui->labPayState->setText("未支付");
        ui->btnIgnorePay->setEnabled(true);
        ui->btnPay->setEnabled(true);
    }else{
        ui->labPayState->setText("已支付");
        ui->btnIgnorePay->setEnabled(false);
        ui->btnPay->setEnabled(false);
    }


    query.exec("select name from tb_user where id="+QString::asprintf("%d",m_orderModel->data(m_orderModel->index(row,2)).toInt()));
    query.first();
    if(query.isValid()){
        ui->labUserName->setText(query.value("name").toString());//用户姓名
    }
    ui->labTime->setText(m_orderModel->data(m_orderModel->index(row,5)).toString());//生成时间


    ui->stackedWidget->setCurrentWidget(ui->pagOrderDetail);
}


void MainWindow::on_btnIgnorePay_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->pagUserOrder);
}


void MainWindow::on_btnPay_clicked()
{
    int result = QMessageBox::question(0,"确认","确认付款?",QMessageBox::Ok|QMessageBox::Cancel,QMessageBox::Ok);
    if(result == QMessageBox::Ok){
        QSqlQuery query;
        if(!query.exec("update tb_order set paystate=1  where id="+ ui->labOrderId->text()+";")){
            QMessageBox::warning(0,"警告","程序出错!");
            return;
        }

        m_orderModel->select();
        ui->actMyorder->trigger();

    }



}


void MainWindow::on_widgetBuy_currentTextChanged(const QString &currentText)
{


}

